import React, { useState, useEffect } from 'react';
import { useEditorStore, useProjectStore } from '../../stores';
import { useMessage } from '../../hooks/useMessage';
import { FaDownload, FaFolder, FaFile, FaPython } from 'react-icons/fa6';
import { Dialog, Button } from '../common';

const ExportDialogSimple = ({ 
  isOpen, 
  onClose
}) => {
  const { getCurrentCode } = useEditorStore();
  const { getAllFiles, getProjectName } = useProjectStore();
  const { success, error, clearMessages } = useMessage();
  const [projectFiles, setProjectFiles] = useState([]);
  const [totalSize, setTotalSize] = useState(0);

  // 格式化文件大小
  const formatFileSize = (bytes) => {
    if (bytes === 0) return '0 B';
    const k = 1024;
    const sizes = ['B', 'KB', 'MB', 'GB'];
    const i = Math.floor(Math.log(bytes) / Math.log(k));
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i];
  };

  // 获取文件图标
  const getFileIcon = (fileName) => {
    const extension = fileName.split('.').pop()?.toLowerCase();
    switch (extension) {
      case 'py':
        return <FaPython style={{ color: '#3776ab', marginRight: '8px' }} />;
      default:
        return <FaFile style={{ color: '#6b7280', marginRight: '8px' }} />;
    }
  };

  // 构建文件的完整路径
  const buildFilePath = (file, allFiles) => {
    if (file.type === 'directory') {
      return null; // 跳过文件夹
    }
    
    const pathParts = [file.name];
    let currentParentId = file.parentId;
    
    // 向上遍历父级目录，构建完整路径
    while (currentParentId && currentParentId !== 'root') {
      const parent = allFiles.find(f => f.id === currentParentId);
      if (parent) {
        pathParts.unshift(parent.name);
        currentParentId = parent.parentId;
      } else {
        break;
      }
    }
    
    return '/' + pathParts.join('/');
  };

  // 当对话框打开时，获取项目文件信息
  useEffect(() => {
    if (isOpen) {
      clearMessages();
      
      // 获取项目文件列表
      const allFiles = getAllFiles();
      
      // 只保留文件，过滤掉文件夹
      const files = allFiles.filter(file => file.type === 'file');
      setProjectFiles(files);
      
      // 计算总文件大小
      const totalSizeBytes = files.reduce((total, file) => {
        return total + (file.content ? new Blob([file.content]).size : 0);
      }, 0);
      setTotalSize(totalSizeBytes);
    }
  }, [isOpen, getAllFiles, clearMessages]);

  const handleDownload = async () => {
    clearMessages();
    
    try {
      // 创建ZIP文件
      const JSZip = (await import('jszip')).default;
      const zip = new JSZip();
      
      // 获取所有文件（包括文件夹）来构建路径
      const allFiles = getAllFiles();
      
      // 添加所有项目文件到ZIP，保持目录结构
      projectFiles.forEach(file => {
        if (file.content) {
          const filePath = buildFilePath(file, allFiles);
          if (filePath) {
            // 移除开头的斜杠，因为JSZip不需要
            const cleanPath = filePath.startsWith('/') ? filePath.slice(1) : filePath;
            zip.file(cleanPath, file.content);
          }
        }
      });
      
      // 生成ZIP文件
      const zipBlob = await zip.generateAsync({ type: 'blob' });
      
      // 创建下载链接
      const url = URL.createObjectURL(zipBlob);
      const projectName = getProjectName() || 'Python作品';
      const zipFileName = `${projectName}.zip`;
      
      const link = document.createElement('a');
      link.href = url;
      link.download = zipFileName;
      link.style.display = 'none';
      
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      
      URL.revokeObjectURL(url);
      success(`作品 ${zipFileName} 导出成功！`);
      
      // 下载成功后关闭对话框
      setTimeout(() => {
        onClose();
      }, 1000);
    } catch (err) {
      console.warn('导出失败:', err);
      error('作品导出失败，请重试');
    }
  };

  return (
    <Dialog
      isOpen={isOpen}
      onClose={onClose}
      title="导出作品"
      size="medium"
      footer={
        <Button
          variant="primary"
          onClick={handleDownload}
          disabled={projectFiles.length === 0}
          style={{ display: 'flex', alignItems: 'center', gap: '8px' }}
        >
          <FaDownload />
          导出作品
        </Button>
      }
    >
      <div style={{ marginBottom: '16px' }}>
        <div style={{ 
          display: 'flex', 
          gap: '8px', 
          marginBottom: '16px',
          flexWrap: 'wrap'
        }}>
          <span style={{
            display: 'inline-flex',
            alignItems: 'center',
            padding: '4px 12px',
            background: 'var(--color-primary)',
            color: 'white',
            borderRadius: '16px',
            fontSize: '13px',
            fontWeight: '500'
          }}>
            {getProjectName() || '未命名作品'}
          </span>
          <span style={{
            display: 'inline-flex',
            alignItems: 'center',
            padding: '4px 12px',
            background: 'var(--color-bg-secondary)',
            color: 'var(--color-text-secondary)',
            border: '1px solid var(--color-border-secondary)',
            borderRadius: '16px',
            fontSize: '13px'
          }}>
            {projectFiles.length} 个文件
          </span>
          <span style={{
            display: 'inline-flex',
            alignItems: 'center',
            padding: '4px 12px',
            background: 'var(--color-success-bg, #d1edff)',
            color: 'var(--color-success, #0c5460)',
            border: '1px solid var(--color-success-border, #bee5eb)',
            borderRadius: '16px',
            fontSize: '13px'
          }}>
            {formatFileSize(totalSize)}
          </span>
        </div>

        <div style={{
          border: '1px solid var(--color-border-secondary)',
          borderRadius: '8px',
          overflow: 'hidden',
          maxHeight: '300px',
          overflowY: 'auto'
        }}>
          <div style={{
            padding: '12px 16px',
            background: 'var(--color-bg-tertiary)',
            borderBottom: '1px solid var(--color-border-secondary)',
            fontSize: '14px',
            fontWeight: '500',
            color: 'var(--color-text-secondary)'
          }}>
            文件列表
          </div>
          <div style={{ padding: '0' }}>
            {projectFiles.length > 0 ? (
              projectFiles.map((file, index) => {
                const allFiles = getAllFiles();
                const filePath = buildFilePath(file, allFiles);
                
                return (
                  <div key={file.id || index} style={{
                    display: 'flex',
                    alignItems: 'center',
                    padding: '12px 16px',
                    borderBottom: index < projectFiles.length - 1 ? '1px solid var(--color-border-light, #f8f9fa)' : 'none',
                    transition: 'background-color 0.2s ease'
                  }}>
                    {getFileIcon(file.name)}
                    <span style={{
                      flex: 1,
                      fontSize: '14px',
                      color: 'var(--color-text-primary)',
                      whiteSpace: 'nowrap',
                      overflow: 'hidden',
                      textOverflow: 'ellipsis',
                      marginRight: '8px',
                      fontFamily: 'var(--font-family-mono, Monaco, Menlo, monospace)'
                    }}>
                      {filePath}
                    </span>
                    <span style={{
                      fontSize: '12px',
                      color: 'var(--color-text-tertiary)',
                      whiteSpace: 'nowrap'
                    }}>
                      {formatFileSize(file.content ? new Blob([file.content]).size : 0)}
                    </span>
                  </div>
                );
              })
            ) : (
              <div style={{
                display: 'flex',
                flexDirection: 'column',
                alignItems: 'center',
                justifyContent: 'center',
                padding: '40px 20px',
                color: 'var(--color-text-tertiary)'
              }}>
                <FaFolder style={{ fontSize: '32px', marginBottom: '8px', opacity: 0.6 }} />
                <span>暂无文件</span>
              </div>
            )}
          </div>
        </div>
      </div>

      <p style={{ 
        margin: 0,
        fontSize: '12px', 
        color: 'var(--color-text-secondary)',
        lineHeight: '1.4',
        textAlign: 'center',
        padding: '12px 16px',
        background: 'var(--color-bg-secondary)',
        borderRadius: '8px',
        borderLeft: '3px solid var(--color-primary)'
      }}>
        💡 提示：导出作品将包含所有项目文件，打包为ZIP格式下载。如果导出失败，请检查浏览器设置或重试。
      </p>
    </Dialog>
  );
};

export default ExportDialogSimple;
